package structure.linkedlist;


/**
* @description: 单向链表
* @author: wangjun
* @create: 2022-04-20
*/
public class SingleLinkedList {

    /**头节点*/
    public HeroNode head = new HeroNode(0,"","");

    /**
     * 无序添加
     *
     * @param node 节点
    */
    public void add(HeroNode node){
        if(head == null){
            System.out.println("链表为空");
            return;
        }
        HeroNode temp = head;
        while (temp.next != null){
            temp = temp.next;
        }
        temp.next = node;
    }

    /**
     * 根据编号添加英雄
     * @param node 节点
    */
    public void addNodeByNo(HeroNode node){
        if(head == null){
            System.out.println("链表为空");
            return;
        }
        boolean flag = false;
        HeroNode temp = head;
        while (temp.next != null){
            if(temp.next.no > node.no){
                flag = true;
                node.next = temp.next;
                temp.next = node;
                break;
            }else if (temp.next.no == node.no){
                throw new RuntimeException("编号为"+node.no+"的节点已存在：");
            }
            temp = temp.next;
        }
        if(!flag){
            temp.next = node;
        }
    }

    /**
     * 打印单链表
    */
    public void print(){
        if(head.next == null){
            System.out.println("链表为空");
            return;
        }
        HeroNode temp = head.next;
        while (temp != null){
            System.out.println(temp);
            temp = temp.next;
        }
    }


    public static void main(String[] args) {
        SingleLinkedList linkedList = new SingleLinkedList();
        HeroNode heroNode1 = new HeroNode(1, "宋江", "及时雨");
        HeroNode heroNode5 = new HeroNode(5, "李逵", "黑旋风");
        HeroNode heroNode3 = new HeroNode(3, "吴用", "智多星");
        HeroNode heroNode4 = new HeroNode(4, "林冲", "豹子头");
        HeroNode heroNode2 = new HeroNode(2, "卢俊义", "玉麒麟");
        HeroNode heroNode10 = new HeroNode(10, "晁盖", "托塔天王");
        linkedList.addNodeByNo(heroNode1);
        linkedList.addNodeByNo(heroNode5);
        linkedList.addNodeByNo(heroNode3);
        linkedList.addNodeByNo(heroNode4);
        linkedList.addNodeByNo(heroNode2);
        linkedList.addNodeByNo(heroNode10);
        System.out.println("添加数据之前：");
        linkedList.print();

        // 抛出异常
//        System.out.println("添加编号为2的数据之后：");
//        HeroNode newHeroNode = new HeroNode(2, "卢俊义", "玉麒麟");
//        linkedList.addNodeByNo(newHeroNode);
//        linkedList.print();

        System.out.println("添加编号为6的数据之后：");
        HeroNode heroNode8 = new HeroNode(8, "刘唐", "赤发鬼");
        linkedList.addNodeByNo(heroNode8);
        linkedList.print();
    }
}